<template>
  <div class="tab">
    <ul class="tab-list">
      <li
        v-for="(tab, index) in tabs"
        class="tab-item"
        :class="{ 'active': index === activeIndex }"
        @click="tabClickHandle(index)"
      >
        <span class="label">{{tab.label}}</span>
      </li>
    </ul>
    <div class="panel">{{tabs[activeIndex].value}}</div>
    <div class="tips">
      <span>提示：</span>
      <pre>{{tips.join('\r\n')}}</pre>
    </div>
  </div>
</template>

<script>
import { ref, getCurrentInstance, onBeforeMount } from 'vue';
export default {
  name: 'Tab',
  setup (props, ctx) {
    const proxy = getCurrentInstance();

    const tabs = ref(Array(3).fill(0).map((n, i) => ({
      id: Math.random().toString().slice(2),
      label: `第${i + 1}个Tab`,
      value: ''
    })));

    const activeIndex = ref(0);

    const tips = ref([]);

    const addRequestStart = index => tips.value.push(`正在发送第${index + 1}个 Tab 的请求. . .`);
    const addRequestEnd = index => tips.value.push(`成功返回第${index + 1}个 Tab 的请求`);
    const addRequestCancelled = index => tips.value.push(`成功取消第${index + 1}个 Tab 的请求！`);

    // 取消请求所需的回调函数
    let currentCancel = null;

    const tabClickHandle = function (index) {
      // 发新请求之前先取消
      if (currentCancel) {
        currentCancel();
        addRequestCancelled(activeIndex.value);
      }
      tabs.value[activeIndex.value].value = '';
      activeIndex.value = index;
      tabs.value[index].value = 'loading. . .';
      addRequestStart(index);
      proxy.ctx.$axios
        .get('/test/' + (index + 1), {
          // 请求时设置取消的回调函数
          cancelToken: new proxy.ctx.$axios.CancelToken(c => { currentCancel = c; })
        })
        .then(res => {
          tabs.value[activeIndex.value].value = res;
          addRequestEnd(index);
          currentCancel = null;
        });
    };

    onBeforeMount(() => {
      tabClickHandle(activeIndex.value);
    });

    return {
      tabs,
      activeIndex,
      tips,
      tabClickHandle,
    }
  }
};
</script>

<style scoped>
.tab {
  display: flex;
}

.tab-list {
  list-style: none;
}

.tab-item {
  box-sizing: border-box;
  width: 150px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  border: 1px solid #333;
  border-right-width: 3px;
  border-right-color: transparent;
  cursor: pointer;
}

.tab-item + .tab-item {
  border-top-width: 0;
}

.tab-item.active {
  border-right-color: #66ccff;
  color: #66ccff;
  /* background-color: #ccc; */
}

.panel {
  float: right;
  width: 600px;
  height: 100%;
}
</style>